// action creaters
export const addTodo = (text) => ({
    type: 'ADD_TODO',
    text
})

export const toggleTodo = (index) => ({
    type: 'TOGGLE_TODO',
    index
})

export const visibilityFilter = (filter) => ({
    type: 'VISIBILITY_FILTER',
    filter
})

// reducers
export const todoApp = (state = {
    visibilityFilter: 'SHOW_ALL',
    todos: []
}, action) => {
    switch (action.type) {
        case 'ADD_TODO':
            return Object.assign({}, state, {
                todos: [
                    ...state.todos,
                    {
                        text: action.text,
                        completed: false
                    }
                ]
            })
        case 'TOGGLE_TODO':
            return Object.assign({}, state, {
                todos: state.todos.map((item, index) => {
                    if (action.index === index) {
                        return Object.assign({}, item, {
                            completed: !item.completed
                        })
                    }
                })
            })
        case 'VISIBILITY_FILTER':
            return Object.assign({}, state, {
                visibilityFilter: action.filter
            })
        default:
            return state;
    }
}